package com.yangfan.thread.thread_wangwenjun17;

import java.util.Arrays;
import java.util.List;

/**
 * 传送带
 */
public class Channel {

    private final static int MAX_REQUEST = 100;

    private final Request[] requestQueue;

    private int head;

    private int tail;

    private int count;

    private final WorkerThread[] workerPool;

    public Channel(int workers) {
        this.requestQueue = new Request[MAX_REQUEST];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
        this.workerPool = new WorkerThread[workers];
        this.init();
    }

    //进行初始化工作者线程(员工)
    private void init() {
        for (int i = 0; i < workerPool.length; i++) {
            workerPool[i] = new WorkerThread("Worker-" + i, this);
        }
    }

    /**
     * 按下开关以启动所有工人上班。
     */
    public void startWorker() {
        Arrays.asList(workerPool).forEach(WorkerThread::start);
    }

    /**
     * 往传送带上面放东西
     * @param request
     */
    public synchronized void put(Request request) {
        while (count >= requestQueue.length) {
            try {
                this.wait();
            } catch (Exception e) {
            }
        }

        //把任务放到最后
        this.requestQueue[tail] = request;
        //如果到了100 则从 0又重新开始 这个小算法经典
        this.tail = (tail + 1) % requestQueue.length;
        this.count++;
        //通知别的线程工作
        this.notifyAll();
    }


    /**
     * 工人从传送带上 拿一个 半成品进行加工
     * @return
     */
    public synchronized Request take() {
        while (count <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //从第一个位置拿
        Request request = this.requestQueue[head];
        //如果 拿到 第一个个了 就重新从 第 0个 开始拿
        this.head = (this.head + 1) % this.requestQueue.length;
        this.count--;
        this.notifyAll();
        return request;
    }
}